﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;

namespace myTravian
{
    public partial class traRobForm2 : Form
    {
        public traRobForm2()
        {
            InitializeComponent();
            cmb_DispatchType.Items.Add("增援");
            cmb_DispatchType.Items.Add("攻擊：正常");
            cmb_DispatchType.Items.Add("攻擊：搶奪");
            cmb_DispatchType.SelectedIndex = 2;
        }

        private void btnGO_Click(object sender, EventArgs e)
        {
            FillTroops2Combobox();
        }

        void FillTroops2Combobox()
        {
            traBrowser1.NavigateURL(txt_url.Text);
            DataTable dt = traBrowser1.GetTroops();
            //基本上應該不會有0，否則就是出錯了..
            if (dt.Rows.Count == 0) 
            {
                MessageBox.Show(traBrowser1.Message);
                return; 
            }
            tra_soldier.SetControlData(dt);
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile1 = new OpenFileDialog();
            openFile1.Filter = "EXCEL Files|*.XLS";

            if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadSheepFromXLS(openFile1.FileName);            
            }
        }

        void LoadSheepFromXLS(string xls)
        {
            string connectionString;
            connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;",xls);

            using(OleDbConnection objConn = new OleDbConnection(connectionString))
            {
                try
                {
                    objConn.Open();
                    OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
                    OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
                    objAdapter1.SelectCommand = objCmdSelect;
                    DataSet objDataset1 = new DataSet();
                    objAdapter1.Fill(objDataset1);
                    objConn.Close();
                    traSheepList.SetData(objDataset1.Tables[0]);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    objConn.Dispose();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "Start")
            {
                button2.Text = "Stop";
                timer1.Interval = Convert.ToInt16(txt_Interval.Text) * 1000;
                timer1.Start();
            }
            else
            {
                button2.Text = "Start";
                timer1.Stop();
            }            
        }

        /// <summary>
        /// 派遣軍隊
        /// </summary>
        private void Dispatch()
        {
            //沒輸入人數也不用出門去了
            if (string.IsNullOrEmpty(txt_soldierCount.Text)) return;

            string[] xyc = { "x", "y", "c" };
            string[] soldierArray = { tra_soldier.GetDisplayText() }; 
            string input, name;
            HtmlElement btn_ok, x, y, c, soldier;
            ArrayList xy = null;

            DataRow rowSoldier = tra_soldier.GetSelectItem();

            //出去的人大於現在在家裏的人，就不要出去了
            if (Convert.ToInt64(rowSoldier[2]) < Convert.ToInt64(txt_soldierCount.Text))
            {
                return;
            }

            DataRow row = traSheepList.GetCurrentRow();

            input = "input";
            name = "name";
            
            xy = traBrowser1.GetElementByName(input, name, xyc);
            x = GetXYElement(xy, "x", name);
            y = GetXYElement(xy, "y", name);
            c = GetXYElement(xy, DispatchType() , "value");

            xy = null;
            xy = traBrowser1.GetElementByName(input, name, new string[] {rowSoldier[1].ToString()} );
            soldier = GetXYElement(xy, rowSoldier[1].ToString(), name); 

            btn_ok = traBrowser1.GetElementByID("btn_ok");

            x.SetAttribute("value", row["X"].ToString());
            y.SetAttribute("value", row["y"].ToString());
            soldier.SetAttribute("value", txt_soldierCount.Text);
            c.SetAttribute("checked", "true");
            btn_ok.InvokeMember("click");

            int i = 0;
            while (true)
            {
                System.Threading.Thread.Sleep(2000);
                Application.DoEvents();
                if (i == 5)
                {
                    break;
                }
                i++;
            }
            btn_ok = traBrowser1.GetElementByID("btn_ok");
            btn_ok.InvokeMember("click");
        }

        private HtmlElement GetXYElement(System.Collections.ArrayList xys, string strXY, string strAttribute)
        {
            HtmlElement xy = null;
            foreach (HtmlElement obj in xys)
            {
                if (obj.GetAttribute(strAttribute).ToLower().Equals(strXY))
                {
                    xy = obj;
                    break;
                }
            }
            return xy;
        }

        private string DispatchType()
        {
            string dispatch;
            switch (cmb_DispatchType.Text)
            {
                case "增援":
                    dispatch = "2";
                    break;
                case "攻擊：正常":
                    dispatch = "3";
                    break;
                case "攻擊：搶奪":
                    dispatch = "4";
                    break;
                default:
                    dispatch = "0";
                    break;
            }
            return dispatch;
        }

        protected void Hijacker()
        {
            FillTroops2Combobox();
            //TODO
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            Hijacker();
            timer1.Start();
        }        
    }
}
